import { videoCutWidth, videoFullWidth } from "../config/index";
import { initialState } from "../const/index";
import { combinedItemsToTextArr, combineItemsBasedOnXDifference, getHHmmss } from "./index";

declare function html2canvas(element: HTMLElement, options?: {
  // 这里可以根据html2canvas的实际API添加选项的类型
  // 例如，width?: number; height?: number;等
}): Promise<HTMLCanvasElement>;

// 通过video组件获取坐标
export const getCanvasByXY = () => {
  return new Promise(async (resolve, reject) => {
    const element = document.getElementById("video-player_html5_api") as HTMLVideoElement;
    const danmu = document.getElementsByClassName(
      "vjs-control vjs-button vjs-danmu-button"
    )?.[0] as HTMLElement;
    if (element.pause) {
      element.pause();
      danmu.click();
    }
    // 截图坐标和尺寸
    const x = element.clientWidth * (videoCutWidth / videoFullWidth); // 起始x坐标
    // const x = 0; // 起始x坐标
    const y = 0; // 起始y坐标
    const width = element.clientWidth * ((videoFullWidth - videoCutWidth) / videoFullWidth); // 截图宽度
    const height = element.clientHeight * (videoFullWidth / videoFullWidth); // 截图高度
    // 截图
    console.log("[zjymock:]", "getCanvasByXY开始", getHHmmss());

    try {
      console.time("[zjymock:] html2canvas裁剪用时");
      const canvas = await html2canvas(element, {
        useCORS: true,
        timeout: 60 * 1000,
        x,
        y,
        width,
        height,
        windowWidth: document.documentElement.scrollWidth,
        windowHeight: document.documentElement.scrollHeight,
      });
      console.timeEnd("[zjymock:] html2canvas裁剪用时");
      console.log("[zjymock:]", canvas);

      element?.play?.();
      // document.body.appendChild(canvas);
      resolve(canvas);
    } catch (error) {
      console.log("[zjymock:]", "裁剪失败，有问题", error);
    }
  });
}

// 根据html2canvas 截图获取文本
export const getTextByCanvas = (): Promise<{
  canvas: any,
  textArr: string[]
}> => {
  return new Promise(async (resolve) => {
    try {
      const canvas = await getCanvasByXY();
      if (!canvas) {
        console.log(
          "[zjymock:]",
          "ggetCanvasByXY 方法超时很多次了，请排查一下"
        );
        return;
      }
      (canvas as any).toBlob(async (blob: any) => {
        const formData = new FormData();
        formData.append("file", blob, "canvas_image.png");

        let textArr = [];
        if (initialState.isMock) {
          textArr = initialState.mockTextArr;
        } else {
          const result = await fetch(`${initialState.uploadHost}/uploadfile`, {
            method: "POST",
            body: formData,
          });
          const res = await result.json();
          textArr = combineItemsBasedOnXDifference(JSON.parse(res.data)?.prism_wordsInfo)
        }

        const handleTextArr = combinedItemsToTextArr(textArr)

        resolve({
          canvas,
          textArr: handleTextArr,
        });
      }, "image/png");
    } catch (error) {
      resolve({
        canvas: null,
        textArr: [],
      });
      console.log("[zjymock:]", error);
    }
  });
}